<template>
  <view class="change-password-container">
    <view class="card-container">
      <!-- 顶部标题区 -->
      <view class="title-area">
        <text class="title-text">首次登录</text>
        <text class="subtitle-text">为了您的账号安全，请修改密码</text>
        <view class="title-line"></view>
      </view>

      <!-- 修改密码表单 -->
      <view class="form-container">
        <view class="input-item" :class="{'error': errors.oldPassword}">
          <text class="icon">🔒</text>
          <input 
            type="password" 
            placeholder="请输入原密码" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.oldPassword"
            @blur="validateOldPassword"
          />
        </view>
        <text v-if="errors.oldPassword" class="error-text">{{ errors.oldPassword }}</text>

        <view class="input-item" :class="{'error': errors.newPassword}">
          <text class="icon">🔑</text>
          <input 
            type="password" 
            placeholder="新密码（至少6位，包含字母和数字）" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.newPassword"
            @blur="validateNewPassword"
          />
        </view>
        <text v-if="errors.newPassword" class="error-text">{{ errors.newPassword }}</text>

        <view class="input-item" :class="{'error': errors.confirmPassword}">
          <text class="icon">✅</text>
          <input 
            type="password" 
            placeholder="确认新密码" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.confirmPassword"
            @blur="validateConfirmPassword"
          />
        </view>
        <text v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</text>

        <button class="action-button" @tap="handleChangePassword">确认修改</button>
        
        <view class="tips-container">
          <text class="tips-title">密码要求：</text>
          <text class="tips-item">• 长度至少6位</text>
          <text class="tips-item">• 必须包含字母</text>
          <text class="tips-item">• 必须包含数字</text>
        </view>
      </view>
    </view>
  </view>
  
  <!-- 修改密码加载弹窗 -->
  <view class="loading-mask" v-if="isLoading">
    <view class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">修改中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import http from '../../utils/request'
import { useUserStore } from '../../store/user'
import { onLoad } from '@dcloudio/uni-app'

// 初始化用户store
const userStore = useUserStore()

// 响应式数据
const form = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const errors = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 加载状态
const isLoading = ref(false)

// 用户信息
const userInfo = ref(null)
const username = ref('')

// 页面加载时获取用户信息
onLoad((options) => {
  console.log('changePassword页面参数:', options)
  
  // 从参数中获取用户名
  if (options && options.username) {
    username.value = options.username
  }
  
  // 从参数中获取用户信息
  if (options && options.userInfo) {
    try {
      userInfo.value = JSON.parse(decodeURIComponent(options.userInfo))
      console.log('解析的用户信息:', userInfo.value)
    } catch (error) {
      console.error('解析用户信息失败:', error)
    }
  }
})

// 验证旧密码
const validateOldPassword = () => {
  if (!form.oldPassword.trim()) {
    errors.oldPassword = '请输入原密码'
    return false
  }
  errors.oldPassword = ''
  return true
}

// 验证新密码
const validateNewPassword = () => {
  if (!form.newPassword.trim()) {
    errors.newPassword = '请输入新密码'
    return false
  }
  
  const password = form.newPassword.trim()
  
  // 检查密码长度
  if (password.length < 6) {
    errors.newPassword = '密码不能少于6位'
    return false
  }
  
  // 检查是否包含字母
  const hasLetter = /[a-zA-Z]/.test(password)
  // 检查是否包含数字
  const hasNumber = /\d/.test(password)
  
  if (!hasLetter || !hasNumber) {
    errors.newPassword = '密码必须包含字母和数字'
    return false
  }
  
  // 检查新密码是否与旧密码相同
  if (password === form.oldPassword.trim()) {
    errors.newPassword = '新密码不能与原密码相同'
    return false
  }
  
  errors.newPassword = ''
  return true
}

// 验证确认密码
const validateConfirmPassword = () => {
  if (!form.confirmPassword.trim()) {
    errors.confirmPassword = '请输入确认密码'
    return false
  }
  if (form.confirmPassword !== form.newPassword) {
    errors.confirmPassword = '两次密码不一致'
    return false
  }
  errors.confirmPassword = ''
  return true
}

// 修改密码
const handleChangePassword = async () => {
  // 验证所有字段
  const isOldPasswordValid = validateOldPassword()
  const isNewPasswordValid = validateNewPassword()
  const isConfirmPasswordValid = validateConfirmPassword()
  
  if (!isOldPasswordValid || !isNewPasswordValid || !isConfirmPasswordValid) {
    return
  }
  
  // 设置加载状态
  isLoading.value = true
  
  try {
    // 准备修改密码的数据
    const changePasswordData = {
      username: userInfo.value['68c37d6a270095f8f3d44245'],
      oldPassword: form.oldPassword.trim(),
      newPassword: form.newPassword.trim(),
      permission: userInfo.value['68c38813270095f8f3d44611'] === '0d4aaef8-d448-47c0-8e29-b4c2172bd236' ? '供应商' : '仓内管理'
    }
    
    console.log('修改密码请求数据:', changePasswordData)
    
    // 调用修改密码的API（这里需要根据实际API调整）
    // 假设有一个修改密码的webhook接口
    const res = await http.post('https://www.dachen.vip/api/workflow/hooks/NjhlY2E1MmEwN2YzYjcwYzRlNTZiMWQ4', changePasswordData)
    
    console.log('修改密码响应:', res)
    
    if(!res || res.data != '修改密码成功'){
      uni.showToast({
        title: '修改失败，请稍后重试',
        icon: 'none',
        duration: 2000
      })
        // 修改成功
    isLoading.value = false
      return
    }
    
    // 修改成功
    isLoading.value = false
    
    uni.showModal({
      title: '修改成功',
      content: '密码修改成功，请使用新密码重新登录',
      showCancel: false,
      success: () => {
        // 清除本地存储的用户信息
        userStore.logout()
        
        // 跳转回登录页
        uni.reLaunch({
          url: '/pages/login/index'
        })
      }
    })
    
  } catch (error) {
    isLoading.value = false
    console.error('修改密码过程发生错误:', error)
    
    // 检查是否是密码错误
    if (error.message && error.message.includes('密码错误')) {
      errors.oldPassword = '原密码错误'
    } else {
      uni.showToast({
        title: '修改失败，请稍后重试',
        icon: 'none',
        duration: 2000
      })
    }
  }
}
</script>

<style scoped>
  .change-password-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background: linear-gradient(135deg, #E8D5FF 0%, #FFB6C1 100%);
    padding: 0 32rpx;
  }

  .card-container {
    width: 85%;
    max-width: 600rpx;
    background: #FFFFFF;
    border-radius: 24rpx;
    box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
    padding: 48rpx 32rpx;
    margin: 48rpx 0;
  }

  .title-area {
    text-align: center;
    margin-bottom: 48rpx;
  }

  .title-text {
    font-size: 48rpx;
    font-weight: bold;
    color: #333333;
    display: block;
    margin-bottom: 16rpx;
  }

  .subtitle-text {
    font-size: 24rpx;
    color: #666666;
    display: block;
    margin-bottom: 16rpx;
  }

  .title-line {
    width: 64rpx;
    height: 4rpx;
    background: #FF6B9B;
    margin: 8rpx auto 0;
    border-radius: 2rpx;
  }

  .form-container {
    width: 100%;
  }

  .input-item {
    display: flex;
    align-items: center;
    background: #FFFFFF;
    border: 2rpx solid #E0E0E0;
    border-radius: 16rpx;
    padding: 0 24rpx;
    height: 104rpx;
    margin-bottom: 8rpx;
    transition: all 0.3s ease;
  }

  .input-item.error {
    border-color: #FF4D4F;
    border-width: 3rpx;
  }

  .icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 20rpx;
    opacity: 0.6;
  }

  input {
    flex: 1;
    font-size: 28rpx;
    color: #333333;
    height: 100%;
    border: none;
    outline: none;
  }

  .error-text {
    color: #FF4D4F;
    font-size: 24rpx;
    margin: 8rpx 0 16rpx 24rpx;
    display: block;
  }

  .action-button {
    width: 100%;
    height: 96rpx;
    background: #FF6B9B;
    border: none;
    border-radius: 24rpx;
    color: #FFFFFF;
    font-size: 32rpx;
    font-weight: bold;
    margin: 32rpx 0;
    box-shadow: 0 4rpx 8rpx rgba(255, 107, 155, 0.3);
    transition: all 0.3s ease;
  }

  .action-button:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 4rpx rgba(255, 107, 155, 0.3);
  }

  .tips-container {
    background: #F5F5F5;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-top: 24rpx;
  }

  .tips-title {
    font-size: 28rpx;
    color: #333333;
    font-weight: bold;
    display: block;
    margin-bottom: 16rpx;
  }

  .tips-item {
    font-size: 24rpx;
    color: #666666;
    display: block;
    margin-bottom: 8rpx;
    line-height: 1.5;
  }

  /* 加载弹窗样式 */
  .loading-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
  }

  .loading-container {
    background: #FFFFFF;
    border-radius: 24rpx;
    padding: 48rpx 64rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
  }

  .loading-spinner {
    width: 64rpx;
    height: 64rpx;
    border: 6rpx solid #F0F0F0;
    border-top: 6rpx solid #FF6B9B;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 24rpx;
  }

  .loading-text {
    font-size: 28rpx;
    color: #333333;
    font-weight: 500;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
</style>

